import React, { useState, useRef, useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import classNames from 'classnames'
import { delTodo, selectAll } from '../../store/actions'
import { changeStatus } from '../../store/actions/todo'

// !常（常量 => actionType）爱（Action => 通过 actionCreator 生成 Action）瑞（Reducer => 处理状态）组（组件里面 dispatch action）优秀！

export default function TodoMain() {
  const list = useSelector((state) => state.todo)
  const dispatch = useDispatch()

  const [currentId, setCurrentId] = useState('')
  // #1. 创建 Ref 引用
  const inputRef = useRef()

  const handleDel = (id) => dispatch(delTodo(id))
  const handleChangeStatus = (id) => dispatch(changeStatus(id))
  // !确定全选的状态，根据所有的单选的状态来确定
  const isCheckAll = list.every((item) => item.done)
  // !全选操作
  const handleChangeAll = () => dispatch(selectAll(!isCheckAll))
  const handleDBLLable = (id) => {
    setCurrentId(id)
    /* setTimeout(() => {
      // #3. 双击聚焦
      inputRef.current.focus()
    }) */
  }
  useEffect(() => {
    // #3. 双击聚焦
    inputRef.current.focus()
    // 期望 currentId 变化完成之后再走
  }, [currentId])
  return (
    <section className='main'>
      <input
        id='toggle-all'
        className='toggle-all'
        type='checkbox'
        checked={isCheckAll}
        onChange={handleChangeAll}
      />
      <label htmlFor='toggle-all'>Mark all as complete</label>
      <ul className='todo-list'>
        {list.map((item) => (
          <li
            key={item.id}
            className={classNames({
              completed: item.done,
              editing: item.id === currentId,
            })}
          >
            <div className='view'>
              <input
                className='toggle'
                type='checkbox'
                checked={item.done}
                onChange={() => handleChangeStatus(item.id)}
              />
              <label onDoubleClick={() => handleDBLLable(item.id)}>
                {item.name}
              </label>
              <button
                className='destroy'
                onClick={() => handleDel(item.id)}
              ></button>
            </div>
            {/* #2. ref 引用和 input 编辑框进行绑定 */}
            <input
              className='edit'
              value='Create a TodoMVC template'
              onChange={() => {}}
              ref={inputRef}
            />
          </li>
        ))}
      </ul>
    </section>
  )
}
